package com.example.demo33.api;

import com.example.demo33.entity.Item;
import com.example.demo33.entity.SellRequest;
import com.example.demo33.entity.User;
import com.example.demo33.mode.UserRepository;
import com.example.demo33.service.ItemService;
import com.example.demo33.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Optional;

@RestController
@RequestMapping("/api/items")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @Autowired
    private UserService userService;

    // 添加饰品
    @PostMapping
    public ResponseEntity<Item> createItem(@RequestBody Item item) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 1. 获取当前用户ID（实际项目中需从数据库查询）
        Long userId = userService.getUserIdByUsername(username);

        // 2. 关联用户（通过User对象，而非直接设置userId）
        User user = new User();
        user.setId(userId); // 仅设置ID即可关联
        item.setUser(user);

        // 3. 保存
        Item savedItem = itemService.saveItem(item);
        return ResponseEntity.ok(savedItem);
    }

    // 查询单个饰品
    @GetMapping("/{id}")
    public ResponseEntity<Item> getItem(@PathVariable Long id) {
        // 验证饰品是否属于当前用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = userService.getUserIdByUsername(auth.getName());

        Optional<Item> item = itemService.getItemById(id);
        if (item.isPresent() && item.get().getUser().getId().equals(userId)) {
            return ResponseEntity.ok(item.get());
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/user/{username}") // 修改路径变量名称为username
    public ResponseEntity<Page<Item>> getItemsByUserId(
            @PathVariable String username, // 参数类型改为String
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "buyTime") String sort,
            @RequestParam(defaultValue = "DESC") String direction,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String search
    ) {
        // 通过username获取userId
        Long userId = userService.getUserIdByUsername(username); // 需要实现这个方法

        if (userId == null) {
            return ResponseEntity.notFound().build(); // 如果用户不存在，返回404
        }

        if (status != null && !status.trim().isEmpty()) {
            return ResponseEntity.ok(
                    itemService.getItemsByUserIdAndStatusAndSearch(
                            userId, status, page, size, Optional.ofNullable(search)
                    )
            );
        } else {
            return ResponseEntity.ok(
                    itemService.getItemsByUserIdAndSearch(
                            userId, page, size, Optional.of(sort), Optional.of(direction), Optional.ofNullable(search)
                    )
            );
        }
    }

    // 删除饰品
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteItem(@PathVariable Long id) {
        // 验证权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = userService.getUserIdByUsername(auth.getName());

        Optional<Item> item = itemService.getItemById(id);
        if (!item.isPresent() || !item.get().getUser().getId().equals(userId)) {
            return ResponseEntity.notFound().build();
        }

        itemService.deleteItem(id);
        return ResponseEntity.noContent().build();
    }

    // 分页查询我的饰品（支持状态和搜索）
    @GetMapping
    public ResponseEntity<Page<Item>> getMyItems(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "buyTime") String sort,
            @RequestParam(defaultValue = "DESC") String direction,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String search
    ) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = userService.getUserIdByUsername(auth.getName());

        if (status != null && !status.trim().isEmpty()) {
            return ResponseEntity.ok(
                    itemService.getItemsByUserIdAndStatusAndSearch(
                            userId, status, page, size, Optional.ofNullable(search)
                    )
            );
        } else {
            return ResponseEntity.ok(
                    itemService.getItemsByUserIdAndSearch(
                            userId, page, size, Optional.of(sort), Optional.of(direction), Optional.ofNullable(search)
                    )
            );
        }
    }

    // 更新饰品
    @PutMapping("/{id}")
    public ResponseEntity<Item> updateItem(@PathVariable Long id, @RequestBody Item updatedItem) {
        // 验证权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = userService.getUserIdByUsername(auth.getName());

        // 检查饰品是否存在且属于当前用户
        Optional<Item> existingItemOptional = itemService.getItemById(id);
        if (!existingItemOptional.isPresent() || !existingItemOptional.get().getUser().getId().equals(userId)) {
            return ResponseEntity.notFound().build();
        }

        Item existingItem = existingItemOptional.get();

        // 防止用户篡改用户关联
        updatedItem.setUser(existingItem.getUser()); // 保持原用户关联

        // 只更新允许修改的字段
        if (updatedItem.getName() != null) {
            existingItem.setName(updatedItem.getName());
        }
        if (updatedItem.getBuyPrice() != null) {
            existingItem.setBuyPrice(updatedItem.getBuyPrice());
        }
        if (updatedItem.getTotalQuantity() != null) {
            existingItem.setTotalQuantity(updatedItem.getTotalQuantity());
        }
        if (updatedItem.getBuyTime() != null) {
            existingItem.setBuyTime(updatedItem.getBuyTime());
        }

        // 确保不能通过编辑接口修改已售出数量和售出价格
        // existingItem.setSoldQuantity(updatedItem.getSoldQuantity()); // 不允许修改
        // existingItem.setSellPrice(updatedItem.getSellPrice()); // 不允许修改

        // 保存更新
        Item savedItem = itemService.saveItem(existingItem);
        return ResponseEntity.ok(savedItem);
    }




    // ItemController.java
// 售出饰品
    @PostMapping("/{id}/sell")
    public ResponseEntity<Item> sellItem(@PathVariable Long id, @RequestBody SellRequest sellRequest) {
        // 验证权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = userService.getUserIdByUsername(auth.getName());

        // 检查饰品是否存在且属于当前用户
        Optional<Item> existingItemOptional = itemService.getItemById(id);
        if (!existingItemOptional.isPresent() || !existingItemOptional.get().getUser().getId().equals(userId)) {
            return ResponseEntity.notFound().build();
        }

        Item existingItem = existingItemOptional.get();

        // 计算可售数量
        int availableQuantity = existingItem.getTotalQuantity() - existingItem.getSoldQuantity();

        // 验证售出数量
        if (sellRequest.getSoldQuantity() <= 0 || sellRequest.getSoldQuantity() > availableQuantity) {
            return ResponseEntity.badRequest().body(null);
        }

        // 计算本次售出总价
        BigDecimal currentSellTotal = sellRequest.getSellPrice().multiply(BigDecimal.valueOf(sellRequest.getSoldQuantity()));

        // 计算历史售出总价（如果已有）
        BigDecimal historicalSellTotal = existingItem.getSellPrice() != null ?
                existingItem.getSellPrice().multiply(BigDecimal.valueOf(existingItem.getSoldQuantity())) :
                BigDecimal.ZERO;

        // 计算新的总售出数量和总售出价格
        int newSoldQuantity = existingItem.getSoldQuantity() + sellRequest.getSoldQuantity();
        BigDecimal newSellTotal = historicalSellTotal.add(currentSellTotal);

        // 设置新的售出信息
        existingItem.setSoldQuantity(newSoldQuantity);
        existingItem.setSellPrice(newSellTotal.divide(BigDecimal.valueOf(newSoldQuantity), 2, RoundingMode.HALF_UP));
        existingItem.setSellTime(LocalDateTime.now()); // 记录最新售出时间

        // 保存更新
        Item savedItem = itemService.saveItem(existingItem);
        return ResponseEntity.ok(savedItem);
    }

}